<template>
  <!-- 页面标题 -->
  <div class="page-header">
    <div class="header-left">
      <div class="icon-wrapper">
        <div class="icon">🌐</div>
      </div>
      <h1 class="title">分布式节点管理</h1>
    </div>
  </div>
  <div class="node-management">
    <!-- 搜索区域 -->
    <div class="search-bar-outer">
      <div class="search-bar-inner">
        <a-input
          v-model:value="searchKeyword"
          placeholder="请输入关键字查询"
          allow-clear
          class="search-input"
          @pressEnter="handleSearch"
          @clear="handleClear"
          :prefix="searchIcon"
        />
        <div class="search-bar-actions">
          <a-dropdown>
            <a-button class="dropdown-btn">
              列表元素
              <DownOutlined />
            </a-button>
            <template #overlay>
              <a-menu @click="handleMenuClick">
                <a-menu-item key="all">全部</a-menu-item>
                <a-menu-item key="success">成功</a-menu-item>
                <a-menu-item key="fail">失败</a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
          <a-button type="primary" class="add-btn" @click="goToCreate"
            >新增</a-button
          >
        </div>
      </div>
    </div>
    <!-- 列表区域 -->
    <div class="node-management-outer">
      <div class="node-management-inner">
        <a-table
          :columns="columns"
          :data-source="paginatedData"
          :row-selection="rowSelection"
          :pagination="false"
          row-key="id"
          :scroll="{ x: 'max-content' }"
          @change="handleTableChange"
          :bordered="false"
        >
          <!-- 表头自定义插槽 -->
          <template #headerCell="{ column }">
            <template v-if="column.dataIndex === 'name'">
              节点名称
              <span class="header-icon">
                <SortAscendingOutlined
                  style="margin-bottom: -2px; color: #bfbfbf; font-size: 14px"
                />
                <SortDescendingOutlined
                  style="
                    margin-left: -2px;
                    margin-bottom: -2px;
                    color: #bfbfbf;
                    font-size: 14px;
                  "
                />
              </span>
            </template>
            <template v-else-if="column.dataIndex === 'type'">
              节点类型
              <span class="header-icon">
                <SortAscendingOutlined
                  style="margin-bottom: -2px; color: #bfbfbf; font-size: 14px"
                />
                <SortDescendingOutlined
                  style="
                    margin-left: -2px;
                    margin-bottom: -2px;
                    color: #bfbfbf;
                    font-size: 14px;
                  "
                />
              </span>
            </template>
            <template v-else-if="column.dataIndex === 'org'">
              责任单位
              <span class="header-icon">
                <SortAscendingOutlined
                  style="margin-bottom: -2px; color: #bfbfbf; font-size: 14px"
                />
                <SortDescendingOutlined
                  style="
                    margin-left: -2px;
                    margin-bottom: -2px;
                    color: #bfbfbf;
                    font-size: 14px;
                  "
                />
              </span>
            </template>
            <template v-else-if="column.dataIndex === 'createTime'">
              创建时间
              <span class="header-icon">
                <SortAscendingOutlined
                  style="margin-bottom: -2px; color: #bfbfbf; font-size: 14px"
                />
                <SortDescendingOutlined
                  style="
                    margin-left: -2px;
                    margin-bottom: -2px;
                    color: #bfbfbf;
                    font-size: 14px;
                  "
                />
              </span>
            </template>
            <template v-else>
              {{ column.title }}
            </template>
          </template>
          <template #status="{ text }">
            <span :class="text === '成功' ? 'status-success' : 'status-fail'">
              {{ text }}
            </span>
          </template>
          <template #enabled="{ record }">
            <a-switch v-model:checked="record.enabled" />
          </template>
          <template #action="{ record }">
            <a-space>
              <a-button type="link" size="small" @click="onEdit(record)">
                <template #icon><EditOutlined /></template>
              </a-button>
              <a-button
                type="link"
                size="small"
                danger
                @click="onDelete(record)"
              >
                <template #icon><DeleteOutlined /></template>
              </a-button>
            </a-space>
          </template>
        </a-table>
        <div class="table-footer-row">
          <div class="footer-left" v-if="paginatedData.length > 0">
            <!-- <a-checkbox :checked="isAllSelected" @change="handleCheckAll">
            全选
          </a-checkbox> -->
            <span style="margin-left: 12px">
              已选择 {{ selectedRowKeys.length }} 条，共 {{ data.length }} 条
            </span>
          </div>
          <a-pagination
            v-model:current="pagination.current"
            v-model:pageSize="pagination.pageSize"
            :total="data.length"
            :show-size-changer="pagination.showSizeChanger"
            :show-quick-jumper="pagination.showQuickJumper"
            :show-total="pagination.showTotal"
            :page-size-options="['10', '20', '50', '100']"
            @change="handlePageChange"
            @showSizeChange="handlePageSizeChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, h, computed, watch } from "vue";
import { useRouter } from "vue-router";
const router = useRouter();
import { message } from "ant-design-vue";
import {
  SearchOutlined,
  DownOutlined,
  EditOutlined,
  DeleteOutlined,
  SortAscendingOutlined,
  SortDescendingOutlined,
} from "@ant-design/icons-vue";

const searchKeyword = ref("");
const searchIcon = h(SearchOutlined);

// 原始数据
const rawData = ref([
  {
    id: 4321,
    name: "L1_JW_BJ_12345",
    type: "集团级",
    org: "哈尔滨工业大学",
    admin: "陆长河",
    phone: "18501239876",
    status: "成功",
    createTime: "2025-10-21 16:34:56",
    enabled: true,
  },
  {
    id: 4322,
    name: "L1_JW_BJ_12346",
    type: "省市级",
    org: "哈尔滨工业大学",
    admin: "陆长河",
    phone: "18501239876",
    status: "失败",
    createTime: "2025-10-21 16:34:56",
    enabled: false,
  },
  {
    id: 4323,
    name: "L1_JW_BJ_12347",
    type: "省市级",
    org: "哈尔滨工业大学",
    admin: "陆长河",
    phone: "18501239876",
    status: "成功",
    createTime: "2025-10-21 16:34:56",
    enabled: true,
  },
  {
    id: 4324,
    name: "L1_JW_BJ_12348",
    type: "区县级",
    org: "哈尔滨工业大学",
    admin: "陆长河",
    phone: "18501239876",
    status: "成功",
    createTime: "2025-10-21 16:34:56",
    enabled: false,
  },
  {
    id: 4325,
    name: "L1_JW_BJ_12349",
    type: "集团级",
    org: "清华大学",
    admin: "张明",
    phone: "13801234567",
    status: "成功",
    createTime: "2025-10-20 10:15:30",
    enabled: true,
  },
  {
    id: 4326,
    name: "L1_JW_BJ_12350",
    type: "省市级",
    org: "北京大学",
    admin: "李华",
    phone: "13909876543",
    status: "失败",
    createTime: "2025-10-19 09:20:15",
    enabled: false,
  },
  {
    id: 4325,
    name: "L1_JW_BJ_12349",
    type: "集团级",
    org: "清华大学",
    admin: "张明",
    phone: "13801234567",
    status: "成功",
    createTime: "2025-10-20 10:15:30",
    enabled: true,
  },
  {
    id: 4326,
    name: "L1_JW_BJ_12350",
    type: "省市级",
    org: "北京大学",
    admin: "李华",
    phone: "13909876543",
    status: "失败",
    createTime: "2025-10-19 09:20:15",
    enabled: false,
  },
  {
    id: 43625,
    name: "L1_JW_BJ_12349",
    type: "集团级",
    org: "清华大学",
    admin: "张明",
    phone: "13801234567",
    status: "成功",
    createTime: "2025-10-20 10:15:30",
    enabled: true,
  },
  {
    id: 43246,
    name: "L1_JW_BJ_12350",
    type: "省市级",
    org: "北京大学",
    admin: "李华",
    phone: "13909876543",
    status: "失败",
    createTime: "2025-10-19 09:20:15",
    enabled: false,
  },
  {
    id: 43235,
    name: "L1_JW_BJ_12349",
    type: "集团级",
    org: "清华大学",
    admin: "张明",
    phone: "13801234567",
    status: "成功",
    createTime: "2025-10-20 10:15:30",
    enabled: true,
  },
  {
    id: 43226,
    name: "L1_JW_BJ_12350",
    type: "省市级",
    org: "北京大学",
    admin: "李华",
    phone: "13909876543",
    status: "失败",
    createTime: "2025-10-19 09:20:15",
    enabled: false,
  },
]);

// 搜索过滤后的数据
const data = computed(() => {
  if (!searchKeyword.value.trim()) return rawData.value;
  const keyword = searchKeyword.value.trim().toLowerCase();
  return rawData.value.filter(
    (item) =>
      item.name.toLowerCase().includes(keyword) ||
      item.type.toLowerCase().includes(keyword) ||
      item.org.toLowerCase().includes(keyword) ||
      item.admin.toLowerCase().includes(keyword) ||
      item.phone.toLowerCase().includes(keyword) ||
      item.status.toLowerCase().includes(keyword) ||
      item.createTime.toLowerCase().includes(keyword)
  );
});

// 分页处理
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: data.value.length,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
});

// 监听搜索和数据变化，自动重置分页和总数
watch([searchKeyword, data], () => {
  pagination.value.current = 1;
  pagination.value.total = data.value.length;
  selectedRowKeys.value = [];
});

// 计算当前页的数据
const paginatedData = computed(() => {
  const startIndex = (pagination.value.current - 1) * pagination.value.pageSize;
  const endIndex = startIndex + pagination.value.pageSize;
  return data.value.slice(startIndex, endIndex);
});

// 多选逻辑
const selectedRowKeys = ref<number[]>([]);
const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: number[]) => {
    selectedRowKeys.value = keys;
  },
  getCheckboxProps: (record: any) => ({
    disabled: !paginatedData.value.some((item) => item.id === record.id),
  }),
}));

function handleSearch() {
  // 这里不需要额外逻辑，watch 已处理分页和选中
  message.success(`搜索内容：${searchKeyword.value}`);
}

function handleClear() {
  searchKeyword.value = "";
  message.info("已清空搜索");
}

function handleMenuClick({ key }: { key: string }) {
  message.info(
    `选择了：${key === "all" ? "全部" : key === "success" ? "成功" : "失败"}`
  );
}

const columns = [
  {
    title: "ID",
    dataIndex: "id",
    width: 80,
    align: "center",
  },
  {
    title: "节点名称",
    dataIndex: "name",
    width: 160,
    align: "center",
    sorter: true,
    slots: { title: "headerCell" },
  },
  {
    title: "节点类型",
    dataIndex: "type",
    width: 100,
    align: "center",
    sorter: true,
    slots: { title: "headerCell" },
  },
  {
    title: "责任单位",
    dataIndex: "org",
    width: 160,
    align: "center",
    sorter: true,
    slots: { title: "headerCell" },
  },
  {
    title: "管理员",
    dataIndex: "admin",
    width: 120,
    align: "center",
  },
  {
    title: "联系电话",
    dataIndex: "phone",
    width: 140,
    align: "center",
  },
  {
    title: "状态",
    dataIndex: "status",
    width: 80,
    align: "center",
    slots: { customRender: "status" },
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    width: 180,
    align: "center",
    sorter: true,
    slots: { title: "headerCell" },
  },
  {
    title: "是否启用",
    dataIndex: "enabled",
    width: 100,
    align: "center",
    slots: { customRender: "enabled" },
  },
  {
    title: "操作",
    dataIndex: "action",
    width: 100,
    align: "center",
    slots: { customRender: "action" },
  },
];

function handleTableChange(paginationObj: any) {
  pagination.value.current = paginationObj.current;
  pagination.value.pageSize = paginationObj.pageSize;
}

function handlePageChange(page: number, pageSize: number) {
  pagination.value.current = page;
  pagination.value.pageSize = pageSize;
}
function handlePageSizeChange(current: number, size: number) {
  pagination.value.current = 1;
  pagination.value.pageSize = size;
  selectedRowKeys.value = [];
}

//  新增
function goToCreate() {
  router.push("/node-add");
}

// 修改
function onEdit(record: any) {
  router.push({
    path: "/node-add",
    query: {
      mode: "edit",
      id: record.id,
      nodeName: record.name,
      nodeType: record.type,
      department: record.org,
      manager: record.admin,
      contactPhone: record.phone,
      status: record.status,
      createTime: record.createTime,
      enabled: record.enabled,
    },
  });
}
function onDelete(record: any) {
  message.info(`删除：${record.name}`);
  // 删除后从选中列表中移除
  selectedRowKeys.value = selectedRowKeys.value.filter(
    (id) => id !== record.id
  );
}
</script>

<style lang="scss" scoped>
// 页面标题
.page-header {
  padding: 0 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 50px;
  background: #fff;

  .header-left {
    display: flex;
    align-items: center;
    gap: 12px;

    .icon-wrapper {
      width: 32px;
      height: 32px;
      background: #1890ff;
      border-radius: 6px;
      display: flex;
      align-items: center;
      justify-content: center;

      .icon {
        font-size: 16px;
        color: white;
      }
    }

    .title {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
      color: #262626;

      @media (max-width: 768px) {
        font-size: 18px;
      }
    }
  }
}

.node-management {
  padding: 16px 24px 0;
  background: #f0f2f5;
  height: 100%;
  min-height: calc(100vh - 50px);
}
// 搜索栏外层，带圆角和阴影
.search-bar-outer {
  padding: 0 0 16px;
}
.search-bar-inner {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  background: #fff;
  border-radius: 8px;
  min-height: 64px;
}

// 输入框样式
.search-input {
  width: 400px;
  height: 40px;
  border-radius: 8px;
  font-size: 16px;
}

// 右侧按钮组
.search-bar-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-left: auto;
}

// 下拉按钮样式
.dropdown-btn {
  height: 40px;
  border-radius: 8px;
  background: #fff;
  border: 1px solid #d9d9d9;
  color: #262626;
  font-weight: 400;
  display: flex;
  align-items: center;
  gap: 4px;
}

// 新增按钮样式
.add-btn {
  height: 40px;
  border-radius: 8px;
  min-width: 72px;
  font-weight: 500;
  font-size: 16px;
  box-shadow: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

// 列表外层，控制间隔和背景
.node-management-outer {
  //   padding: 16px 0 16px; // 与上方间隔16px，两侧内边距16px
  min-height: 0;
}

// 列表内层，圆角和阴影
.node-management-inner {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px 0 rgba(44, 56, 82, 0.06);
  padding: 0 0 0 0;
  //   min-height: 400px;

  .ant-table-wrapper {
    border-radius: 12px;
    overflow: hidden;
  }

  .status-success {
    color: #12c189;
    background: #e6f7f1;
    border-radius: 4px;
    padding: 2px 8px;
    font-size: 14px;
    display: inline-block;
  }
  .status-fail {
    color: #ff4d4f;
    background: #fff1f0;
    border-radius: 4px;
    padding: 2px 8px;
    font-size: 14px;
    display: inline-block;
  }
}

// 表头排序图标样式
.header-icon {
  margin-left: 2px;
  display: inline-block;
  vertical-align: middle;
}

// 分页器一排，左侧放全选，右侧放分页
.table-footer-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px 16px 24px;
  .ant-pagination {
    margin: 0;
  }

  .footer-left {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #666;

    .ant-checkbox-wrapper {
      font-size: 14px;
    }
  }
}

// 修复表格行选择框的样式
:deep(.ant-table-selection-column) {
  width: 60px !important;
  text-align: center;
}

:deep(.ant-checkbox-inner) {
  border-radius: 4px;
}

:deep(.ant-table-row-selected > td) {
  background: #f5faff !important;
}

// 表格紧凑行高和字体
:deep(.ant-table) {
  //   font-size: 14px;
}
:deep(.ant-table-thead > tr > th) {
  padding-top: 8px !important;
  padding-bottom: 8px !important;
  font-size: 14px;
}
:deep(.ant-table-tbody > tr > td) {
  padding-top: 6px !important;
  padding-bottom: 6px !important;
  font-size: 14px;
}
:deep(.ant-table-tbody > tr) {
  //   height: 36px !important;
  min-height: 36px !important;
}

// 复选框更小
// :deep(.ant-checkbox-inner) {
//   width: 14px !important;
//   height: 14px !important;
// }

// 操作按钮更紧凑
// :deep(.ant-btn-link) {
//   padding: 0 4px !important;
//   font-size: 13px !important;
//   height: 24px !important;
//   line-height: 24px !important;
// }

// 分页器区域更紧凑
// .table-footer-row {
//   padding: 8px 24px 8px 24px;
//   font-size: 13px;
//   .ant-pagination {
//     font-size: 13px;
//   }
// }

// 选中行背景色
// :deep(.ant-table-row-selected > td) {
//   background: #f5faff !important;
// }
</style>
